#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import argparse
import logging
from trustimage.core.version import VERSION
from trustimage.utils.command_registry import CommandRegistry

def setup_logging(verbose=False):
    """Set log level and format"""
    log_level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=log_level,
        format='%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d %(message)s',
    )

def main():
    """Main entry function, parses command line arguments and dispatches to the corresponding command handler"""
    parser = argparse.ArgumentParser(
        description='TrustImage - VM image customization tool',
        prog='trustimage'
    )
    parser.add_argument('--version', action='version', version=f'TrustImage {VERSION}')
    parser.add_argument('-v', '--verbose', action='store_true', help='Show verbose log')

    # Create subcommand parser
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Automatically discover and register commands
    registry = CommandRegistry.autodiscover('trustimage.commands')
    
    # Add all commands to subparser
    for cmd_name, help_text in registry.get_all_commands():
        cmd_parser = subparsers.add_parser(cmd_name, help=help_text)
        registry.setup_command(cmd_name, cmd_parser)
    
    # Parse command line arguments
    args = parser.parse_args()
    
    # Set log
    setup_logging(args.verbose)
    
    # If no command specified, show help
    if not args.command:
        parser.print_help()
        return 1
    
    # Get command handler and execute
    cmd_handler = registry.get_command(args.command)
    if not cmd_handler:
        parser.print_help()
        return 1
    
    try:
        return cmd_handler(args)
    except Exception as e:
        logging.exception(f"Error occurred while executing command {args.command}: {e}")
        return 1
    
if __name__ == '__main__':
    sys.exit(main()) 